<template>
  <el-card class="join-class-card">
    <template #header>
      <div class="card-header">
        <span>加入班级</span>
      </div>
    </template>

    <el-form :model="form" label-width="100px" @submit.prevent="handleJoin">
      <el-form-item label="邀请码" prop="invitationCode">
        <el-input v-model="form.invitationCode" placeholder="请输入班级邀请码" />
      </el-form-item>

      <el-form-item>
        <el-button :loading="loading" type="primary" @click="handleJoin">加入班级</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card class="joined-class-list" style="margin-top: 30px">
    <template #header>
      <div class="card-header">
        <span>我加入的班级</span>
      </div>
    </template>

    <el-table
      v-loading="loadingClasses"
      :data="joinedClasses"
      row-key="classId"
      style="width: 100%"
    >
      <el-table-column label="班级名称" prop="className" />
      <el-table-column label="学科" prop="subject" />
      <el-table-column label="任课老师" prop="teacherName" />
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button style="color: #409eff" type="text" @click="showStudents(scope.row)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <el-dialog
    :model-value="studentsDialogVisible"
    title="班级学生列表"
    width="400px"
    @update:model-value="(val) => (studentsDialogVisible = val)"
  >
    <el-scrollbar style="max-height: 400px">
      <el-row
        v-for="student in studentsInClass"
        :key="student.userId"
        :gutter="12"
        align="middle"
        style="margin-bottom: 12px"
      >
        <el-col :span="6">
          <el-avatar :src="student.avatar" />
        </el-col>
        <el-col :span="18">
          {{ student.nickname }}
        </el-col>
      </el-row>
    </el-scrollbar>

    <template #footer>
      <el-button @click="studentsDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { apiClient, handleErrorAndRedirect } from '@/api'

const form = reactive({
  invitationCode: '',
})

const loading = ref(false)
const loadingClasses = ref(false)
const joinedClasses = ref<any[]>([])

const studentsDialogVisible = ref(false)
const studentsInClass = ref<any[]>([])

const fetchJoinedClasses = async () => {
  loadingClasses.value = true
  try {
    const res = await apiClient.get('/classes/join/list')
    joinedClasses.value = res.data
  } catch (error) {
    handleErrorAndRedirect(error, '获取已加入班级失败')
  } finally {
    loadingClasses.value = false
  }
}

const handleJoin = async () => {
  if (!form.invitationCode.trim()) {
    ElMessage.warning('请输入邀请码')
    return
  }

  loading.value = true
  try {
    await apiClient.post(`/classes/join/${form.invitationCode}`)
    ElMessage.success('加入成功')
    await fetchJoinedClasses()
  } catch (error) {
    ElMessage.error('加入失败，请检查邀请码是否正确')
  } finally {
    loading.value = false
  }
}

const showStudents = async (cls: any) => {
  try {
    const res = await apiClient.get(`/classes/${cls.classId}/students`)
    studentsInClass.value = res.data
    studentsDialogVisible.value = true
  } catch (error) {
    handleErrorAndRedirect(error, '获取学生列表失败')
  }
}

onMounted(() => {
  fetchJoinedClasses()
})
</script>

<style scoped>
.join-class-card {
  max-width: 500px;
  margin: 80px auto 20px;
}

.joined-class-list {
  max-width: 700px;
  margin: 0 auto 50px;
}

.el-avatar {
  vertical-align: middle;
}
</style>
